<?php

namespace backend\modules\ding\controllers;

use common\enums\WhetherEnum;
use common\helpers\Html;
use common\models\ding\Check;
use common\models\personnel\Personnel;
use Yii;
use common\models\base\SearchModel;
use common\traits\Curd;
use common\models\personnel\Branch;
use common\enums\StatusEnum;
use backend\controllers\BaseController;
use yii\db\Query;

/**
 * 客户端
 *
 * Class ClientController
 * @package backend\modules\member\controllers
 * @author jianyan74 <751393839@qq.com>
 */
class BranchController extends BaseController
{
    use Curd;

    /**
     * @var Client
     */
    public $modelClass = Check::class;

    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $id=Yii::$app->request->get('name_id');
        $data = self::actionStatistics($id);

        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => ['position'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);
        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
//            $late = Late;
        $dataProvider->query->where(['userId'=>$id])
            ->andWhere(['timeresult'=>WhetherEnum::Late]);;
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'user_id'=>$id,
            'statistics'=>$data,
        ]);
    }
    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id');
        $sid= Yii::$app->request->get('sid');
        $model = $this->findModel($id);
        $model->user=$sid;
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(Yii::$app->request->referrer)
                : $this->message($this->getError($model), $this->redirect(Yii::$app->request->referrer), 'error');
        }
        return $this->renderAjax($this->action->id, [
            'model' => $model,
            'menuDropDownList' => Yii::$app->services->menu->getDropDownts(),
            'user_id'=>$sid,
        ]);
    }
    public static function actionStatistics($id){

        $data = Branch::find()
            ->where(['user'=>$id,'status'=>1])
            ->asArray()
            //->createCommand()->getRawSql();
            ->all();

        $arr = array_column($data,'fraction');
        $arre = array_sum($arr);

        $data =Personnel::updateAll(['integral'=>$arre],['personnel_id'=>$id]);
        return $arre;

    }
}